package reflect;

import java.lang.reflect.Field;

public class GetField {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        /*
        Class类中用于获取成员变量的方法：
            返回所有公共成员变量对象的数组
            Field[] getFields()
            返回所有有成员变量对象的数组
            Field[] getDeclaredFields()
            返回单个公共成员变量对象
            Field getField(String name)
            返回单个成员变量对象
            Field getDeclaredField(String name)

       Field类中用于创建对象的方法：
            void set(Object obj, Object value)：赋值，传入对象
            Object get(Object obj)：获取值，传入对象
         */

        //1.获取class字节码文件的对象
        Class clazz = Class.forName("reflect.Student3");

        //2.获取(所有)成员变量
        //Field[] fields = clazz.getFields();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            System.out.println(field);
        }

        //获取单个的成员变量
        Field name = clazz.getField("name");
        System.out.println(name);

        Field age = clazz.getDeclaredField("age");
        System.out.println(age);

        //获取权限修饰符
        int modifiers = name.getModifiers();
        System.out.println(modifiers);

        //获取成员变量的名字
        String n = name.getName();
        System.out.println(n);

        //获取成员变量的数据类型
        Class<Student3> type = (Class<Student3>) name.getType();
        System.out.println(type);

        //获取成员变量的值
        Student3 student3 = new Student3("zs",23);
        String str = (String) name.get(student3);
        System.out.println(str);

        //修改对象里面记录的值
        name.set(student3,"ls");

        age.setAccessible(true);//暴力反射
        age.set(student3,20);
        System.out.println(student3);


    }
}
class Student3 {
    public String name;
    private int age;

    public Student3() {
    }
    private Student3(String name) {
        this.name = name;
    }
    private Student3(int age) {
        this.age = age;
    }

    public Student3(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student3{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
